﻿using System;
using System.Xml.Linq;
using BattleFury.Lib.Extensions;
using BattleFury.Lib.Input;
using Microsoft.Xna.Framework;

namespace BattleFury.Lib.Controls
{
	public class CheckBox
		: Control
	{
		private string _state = "CheckBox";

		public bool IsChecked { get; set; }
		public Color HighlightColor { get; set; }

		public CheckBox()
		{
			HighlightColor = Color.Yellow;
			Size = new Vector2(32f, 32f);
		}

		#region Serialization

		public override void Serialize()
		{
			throw new NotImplementedException();
		}

		public override void Deserialize(XElement element, object callingObject)
		{
			base.Deserialize(element, callingObject);

			IsChecked = element.GetBoolean("IsChecked");
			HighlightColor = element.GetColor("HighlightColor", Color.Yellow);

			var width = element.GetInt("Width", 32);
			var height = element.GetInt("Height", 32);

			Size = new Vector2(width, height);
		}

		#endregion

		public override void Update(GameTime gameTime)
		{
			_state = "CheckBox";

			if (Input.Mouse.CurrentBounds.Intersects(Bounds))
			{
				_state = "CheckBoxHighlighted";
				if (Input.Mouse.IsMouseButtonPressed(MouseButtons.Left))
				{
					IsChecked = !IsChecked;
				}
			}

			if (_state == "CheckBox" && IsChecked)
			{
				_state = "CheckBoxChecked";
			}
			else if (_state == "CheckBoxHighlighted" && IsChecked)
			{
				_state = "CheckBoxCheckedHighlighted";
			}

			if (!IsEnabled)
			{
				_state = "CheckBoxDisabled";
				if (IsChecked)
				{
					_state = "CheckBoxCheckedDisabled";
				}
			}
		}

		public override void Draw(GameTime gameTime)
		{
			var tint = Tint;
			if (_state.Contains("Highlighted"))
			{
				tint = HighlightColor;
			}
			SpriteBatch.Draw(Texture, Bounds, Skin[_state].SourceBounds, tint);
		}
	}
}